<?php
session_start();
if(isset($_SESSION['userNum']) && $_SESSION['voter_permission'] == 'Admin'){
$userNum = $_SESSION['userNum'];
$pageTitle = $_SESSION['title'];
$server = $_SESSION['server'];
$user = $_SESSION['user'];
$pass = $_SESSION['pass'];
$db = $_SESSION['db'];

$ifLoginIsSingle = checkSessionID($_SESSION['sid'],$userNum,$server,$user,$pass,$db);
		
		if($ifLoginIsSingle == "False"){
			session_destroy(); 
			header('Location: home.php');
		}

}else{
header('Location: home.php');
}

$case = "";

if($_POST['voteAction']=='Show Results'){
	
	$case = "case1";

}else if($_POST['voteAction']=='Add Voting Results'){
	
	$myFile = "news.txt";
	$fh = fopen($myFile,'a') or die ("Can't open file");
	$date= "As of ".(date("l , jS \of F Y h:i:s A"));
	$voteResults = $date.", <font color=red><b>Results of Election<b></font> ,";
	mysql_connect($server,$user,$pass) or die(mysql_error());
	mysql_select_db($db) or die(mysql_error());
	$positionNum = mysql_query("SELECT * from positions");

		while($row = mysql_fetch_array( $positionNum )){
		$tmpPosNum = $row['pos_num'];
		$tmpPosLimit = $row['pos_vote_limit'];
		$voteResults = $voteResults.",<font color=yellow>".$row['pos_name']."</font> - ";
		$votesUpdate = mysql_query("SELECT c.cand_name, c.cand_party as 'Candidate',count(*) as 'Votes' from candidates c,vote_count v where v.voted_cand_num = c.cand_num and c.cand_pos = '".$tmpPosNum."' group by cand_num order by Votes desc");
			while($row2 = mysql_fetch_array( $votesUpdate )){
			$voteResults = $voteResults.$row2['cand_name']." - ".$row2['Votes']."&nbsp &nbsp &nbsp ";
			}	
		}	

	fwrite($fh,$voteResults);
	fclose($fh);
	$case = "case2";

}else if($_POST['voteAction']=='Update'){
	
	$myFile = "news.txt";
	$fh = fopen($myFile,'w') or die ("Can't open file");
	fwrite($fh,$_POST['news']);
	fclose($fh);
	$case = "case3";

}else if($_POST['voteAction']=='Clear'){
	
	$myFile = "news.txt";
	$fh = fopen($myFile,'w') or die ("Can't open file");
	fwrite($fh,"");
	fclose($fh);
	$case = "case2";

}else if($_POST['voteAction']=='Edit News'){

	$case = "case2";

}else if($_POST['voteAction']=='Close Vote'){

	mysql_connect($server,$user,$pass) or die(mysql_error());
	mysql_select_db($db) or die(mysql_error());
	mysql_query("UPDATE positions SET pos_close_vote =  '1' WHERE pos_name = '".$_POST['posName']."'");	
	header('Location: admin.php');

}else if($_POST['voteAction']=='Open Vote'){
	
	mysql_connect($server,$user,$pass) or die(mysql_error());
	mysql_select_db($db) or die(mysql_error());
	mysql_query("UPDATE positions SET pos_close_vote =  '0' WHERE pos_name = '".$_POST['posName']."'");	
	header('Location: admin.php');
	
}else if($_POST['voteAction']=='Reset Vote'){

	mysql_connect($server,$user,$pass) or die(mysql_error());
	mysql_select_db($db) or die(mysql_error());
	mysql_query("DELETE FROM vote_count USING vote_count,candidates WHERE vote_count.Voted_Cand_Num  = candidates.Cand_Num AND candidates.Cand_POS = '".$_POST['posNum']."'");	
	header('Location: admin.php');
	
}else if($_POST['voteAction']=='Edit Position'){

	header('Location: posEdit.php');

}
else if($_POST['voteAction']=='Edit Candidate'){

	header('Location: candEdit.php');

	}
?>
<html>
<head>
<title>Administrator - <?php echo $pageTitle ?></title>
<?php include('showIcon.php'); ?>
</head>
<body style="background-image:url('images/bg_blue.jpg')">
<div style="position:absolute;left:75px;top: 0px">
<font face = "Arial">
<table style="width: 810px; height: 104px" border="0" cellspacing="0" cellpadding="0" class="style1">
<?php include("menuButtons.php"); ?>
</table>
<table style="width: 810px;" cellspacing="0" cellpadding="0" class="style2">
<tr>
<td style="height: 76px; width: 28px;"></td>
<td style="height: 76px" width="808px">

<?php
if($case == "case1"){


echo "<br>";
echo "As of ".(date("l , jS \of F Y h:i:s A") . "<br />");

mysql_connect($server,$user,$pass) or die(mysql_error());
mysql_select_db($db) or die(mysql_error());
$positions = mysql_query("Select * from positions");

while($row = mysql_fetch_array($positions))
{		
		$limit = $row['pos_vote_limit'];
		$ctr = 0;
		$arrInfo=array();
		$arrCount=array();			
		
		mysql_connect($server,$user,$pass) or die(mysql_error());
		mysql_select_db($db) or die(mysql_error());
		$candidates = mysql_query("Select * from candidates where Cand_Pos = '".$row['pos_num']."'");
		
		$tempPosName = $row['pos_name'];
		$tempPosNum = $row['pos_num'];
		$tempPosLimit = $row['pos_vote_limit'];
		
			while($candInfo = mysql_fetch_array($candidates))
			{
					$tempCandName=$candInfo['Cand_Name'];
					$tempCandParty=$candInfo['Cand_Party'];
					$tempCandNum = $candInfo['Cand_Num'];
					$arrInfo[$ctr] = $tempCandName."|".$tempCandParty;
			
					mysql_connect($server,$user,$pass) or die(mysql_error());
					mysql_select_db($db) or die(mysql_error());
					$voteResults = mysql_query("SELECT c.cand_name as 'pangalan', c.cand_party as 'Candidate',count(*) as 'Votes' from candidates c,vote_count v where v.voted_cand_num = '".$tempCandNum."' and c.cand_pos = '".$tempPosNum."' group by cand_num order by Votes desc");
			
					$count = 0;	
					
					while($voteCounts = mysql_fetch_array($voteResults)){
					$count = $voteCounts['Votes'];
					}
					
					$arrCount[$ctr] = $count;
					$ctr = $ctr+1;
					
			}
			
		$ctr2 = 0;
		echo "<br><table border = '0' width = '600px'><tr><td colspan='3' width='320'><h4>".$tempPosName." - Election Results</td></tr>";
		echo "<tr style = 'background-color:silver'><td width = '200px'>Name</td><td  width = '100px'>Party</td><td  width = '50px'>Votes</td></tr>";
		$sorted = insertionSort($arrCount,$arrInfo,count($arrInfo));
		while($ctr2 < count($sorted)){
			$pieces = explode("|",$sorted[$ctr2]);
			echo "<tr><td>".$pieces[0]."</td><td>".$pieces[1]."</td><td align = 'center'>".$pieces[2]."</td></tr>";
			$ctr2 = $ctr2 + 1;
		}
		echo "</table>";
		}

}

if($case == "case2"){
echo "<br><br>";
echo "<h2>Edit the news</h2>";
echo "<form method='post' action='control.php'><table width = '550px'>";
echo "<tr><td>Type the news in the text area - Seperate them by comma</td></tr>";
echo "<tr><td><textarea name='news' style='width:400px;height:200px'>";
include ("news.txt");
echo "</textarea></td></tr>";
echo "<tr><td><input style='background-color:#0066CC' type='submit' name = 'voteAction' value='Update'>&nbsp";
echo "<input style='background-color:#0066CC' type='submit' name = 'voteAction' value='Clear'>&nbsp";
echo "<input style = 'background-color:#CCCCCC' type = 'submit' name = 'voteAction' value = 'Add Voting Results'></td></tr></table></form>";
}else if($case == "case3"){

echo "<br><strong>Successfully edited the news</strong><br><br><a href='home.php'>See the news</a>";

}

function insertionSort($list,$names, $length) {
    $firstOutOfOrder= 0;
	$location= 0; 
	$temp="";
	$temp2="";
   
    for($firstOutOfOrder = 1; $firstOutOfOrder < $length; $firstOutOfOrder+=1) { //Starts at second term, goes until the end of the array.
        if($list[$firstOutOfOrder] > $list[$firstOutOfOrder - 1]) { //If the two are out of order, we move the element to its rightful place.
            $temp = $list[$firstOutOfOrder];
			$temp2 = $names[$firstOutOfOrder];
            $location = $firstOutOfOrder;
           
            do { //Keep moving down the array until we find exactly where it's supposed to go.
                $list[$location] = $list[$location-1];
				$names[$location] = $names[$location-1];
                $location-=1;
            }while (($location < 0) && ($list[$location-1] < $temp));
           
            $list[$location] = $temp;
			$names[$location] = $temp2;
			
        }
    }
	
	$ctr = 0;
	while($ctr < count($list)){
	$newArray[$ctr] = $names[$ctr]."|".$list[$ctr];
	$ctr+=1;
	}
	return $newArray;
}
//Function checkSessionID()
// -Checks if session in db is same in the session in browser
// If not, it logs out
function checkSessionID($sid,$uname,$sver,$usr,$passwd,$dbase){
mysql_connect($sver,$usr,$passwd) or die(mysql_error());
mysql_select_db($dbase) or die(mysql_error());

	$querySession = mysql_query("SELECT voter_current_session from voters WHERE voter_num = '".$uname."'");	

		while($sessionInDB = mysql_fetch_array($querySession)){
		$loggedSession = $sessionInDB['voter_current_session'];
		}

	if($_SESSION['sid'] == $loggedSession){
	return "True";
	}else{
	return "False";
	}	
}
?>
</td>
</tr>
</table>
<br><br><br><br><br>
</div>
<div style="position:fixed;left:72px;bottom: -5px">
<table>
<tr>
<td width="8px" colspan="2"><img src="images/end.png"></td>
</tr>
</table>
</div>
</body>
</html>
